package com.mainbo.modular.system.controller.xymh;

import cn.stylefeng.roses.core.base.controller.BaseController;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.ctrip.framework.apollo.ConfigService;
import com.mainbo.core.common.constant.ApolloConstants;
import com.mainbo.core.shiro.SessionKey;
import com.mainbo.core.shiro.ShiroKit;
import com.mainbo.core.util.Result;
import com.mainbo.modular.system.model.PtOrg;
import com.mainbo.modular.system.model.PtResources;
import com.mainbo.modular.system.model.meta.ConfigConstants;
import com.mainbo.modular.system.model.meta.MetaUtils;
import com.mainbo.modular.system.service.IPtResourcesService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import com.mainbo.core.log.LogObjectHolder;
import com.mainbo.modular.system.model.PtAnnouncement;
import com.mainbo.modular.system.service.IPtAnnouncementService;

import javax.annotation.Resource;
import java.sql.Connection;
import java.util.*;

/**
 * 控制器
 *
 * @author xww
 * @Date 2020-03-11 11:19:04
 */
@Controller
@RequestMapping("/ptAnnouncement")
public class PtAnnouncementController extends BaseController {
    private static final Logger logger= LoggerFactory.getLogger(PtAnnouncementController.class);

    private String PREFIX = "/system/xymh/notice/";

    @Resource
    private IPtAnnouncementService ptAnnouncementService;
    @Resource
    private IPtResourcesService resourcesService;

    /**
     * 跳转到首页
     */
    @RequestMapping("")
    public String index(Model model) {

        PtOrg org = ShiroKit.getSessionAttr(SessionKey.CURRENT_ORG);
        if ((org == null)) {
            model.addAttribute("orgId", "0");
            return PREFIX + "notice_org.html";
        }
        model.addAttribute("orgId", org.getId());
        return PREFIX + "notice_index.html";
    }
    @RequestMapping("noticeList")
    public String noteList(Model model,String orgId) {
        model.addAttribute("orgId", orgId);
        return PREFIX + "notice_list.html";
    }
    @RequestMapping("noticeDraft")
    public String noteDraft(Model model,String orgId) {
        model.addAttribute("orgId", orgId);
        return PREFIX + "notice_draft.html";
    }
    /**
     * 跳转到添加
     */
    @RequestMapping("/ptAnnouncement_add")
    public String ptAnnouncementAdd(Model model,String orgId) {
        model.addAttribute("orgId",orgId);
        model.addAttribute("types", MetaUtils.listMeta(ConfigConstants.SYS_TZGG_TYPE_CODE));
        model.addAttribute("uploadUrl", ApolloConstants.readUploadUrl());
        model.addAttribute("storageUrl", ApolloConstants.readStorageUrl());
        return PREFIX + "notice_add.html";
    }

    /**
     * 跳转到修改
     */
    @RequestMapping("/ptAnnouncement_update/{ptAnnouncementId}")
    public String ptAnnouncementUpdate(@PathVariable Integer ptAnnouncementId, Model model) {
        PtAnnouncement ptAnnouncement = ptAnnouncementService.selectById(ptAnnouncementId);
        model.addAttribute("item",ptAnnouncement);
        model.addAttribute("uploadUrl", ConfigService.getConfig("ucenter.front").getProperty("upload_url",""));
        model.addAttribute("storageUrl", ApolloConstants.readStorageUrl());
        model.addAttribute("types", MetaUtils.listMeta(ConfigConstants.SYS_TZGG_TYPE_CODE));
        getAnnunciateAttachs(ptAnnouncement.getAttachs(), model);
        LogObjectHolder.me().set(ptAnnouncement);
        return PREFIX + "notice_edit.html";
    }

    /**
     * 获取通告附件
     *
     * @param attachs
     *          String
     * @param m
     *          Model
     */
    public void getAnnunciateAttachs(String attachs, Model m) {
        List<PtResources> rList = new ArrayList<PtResources>();
        if (StringUtils.isNotBlank(attachs)) {
            String[] att = attachs.split("#");
            List<String> idLists = new ArrayList<String>();
            for (int i = 0; i < att.length; i++) {
                PtResources resource = resourcesService.selectById(att[i]);
                rList.add(resource);
                idLists.add(att[i]);
            }
            m.addAttribute("idLists", idLists);
        }
        m.addAttribute("rList", JSON.toJSONString(rList));

    }

    /**
     * 获取列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(PtAnnouncement announcement) {
        EntityWrapper<PtAnnouncement> wrapper=new EntityWrapper<>();
         if (StringUtils.isNotBlank(announcement.getTitle())){
             wrapper.like("title",announcement.getTitle());
         }
         wrapper.eq("org_id",announcement.getOrgId());
         wrapper.eq("is_draft",0);
        wrapper.orderDesc( Collections.singleton("is_top"));
        wrapper.orderDesc( Collections.singleton("crt_dttm"));
        List<PtAnnouncement> list= ptAnnouncementService.selectList(wrapper);
        for (PtAnnouncement announcement1:list){
            announcement1.setTzggTypeName(MetaUtils.getMeta(announcement1.getTzggType()).getName());
        }

        return list;
    }
    /**
     * 获取草稿箱列表
     */
    @RequestMapping(value = "/draftList")
    @ResponseBody
    public Object draftList(PtAnnouncement announcement) {
        EntityWrapper<PtAnnouncement> wrapper=new EntityWrapper<>();
        if (StringUtils.isNotBlank(announcement.getTitle())){
            wrapper.like("title",announcement.getTitle());
        }
        wrapper.eq("org_id",announcement.getOrgId());
        wrapper.eq("is_draft",1);
        wrapper.orderBy("crt_dttm",false);
        List<PtAnnouncement> list= ptAnnouncementService.selectList(wrapper);
        for (PtAnnouncement announcement1:list){
            announcement1.setTzggTypeName(MetaUtils.getMeta(announcement1.getTzggType()).getName());
        }

        return list;
    }

    /**
     * 新增或修改通告
     */
    @RequestMapping(value = "/saveOrUpdate")
    @ResponseBody
    public Object add(PtAnnouncement ptAnnouncement) {
        Result result = new Result();

        result.setMsg("操作成功");
        try {

            ptAnnouncementService.saveAnnunciate(ptAnnouncement);
            result.setCode(Result.SUCCESS);
        } catch (Exception e) {
            result.setCode(Result.FAIL);
            result.setMsg("保存失败");
            logger.error("通知公告-后台-保存失败", e);
        }
        return result;
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete/{id}")
    @ResponseBody
    public Result delete(@PathVariable Integer id) {
        Result result = new Result();
        try {
            ptAnnouncementService.deleteAnnunciate(id);
            result.setMsg("删除成功！");
            result.setCode(Result.SUCCESS);
        } catch (Exception e) {
            result.setCode(Result.FAIL);
            result.setMsg("删除失败！");
            logger.error("刪除通知公告失败", e);
        }
        return result;
    }

    /**
     * 详情
     */
    @RequestMapping(value = "/detail/{ptAnnouncementId}")
    public String detail(@PathVariable("ptAnnouncementId") Integer ptAnnouncementId,Model model) {
        PtAnnouncement announcement=ptAnnouncementService.selectById(ptAnnouncementId);
        if (announcement != null) {
            getAnnunciateAttachs(announcement.getAttachs(), model);
        }
        model.addAttribute("announcement",announcement);
        model.addAttribute("tzggTypeName",MetaUtils.getMeta(announcement.getTzggType()).getName());
        return  PREFIX + "notice_info.html";
    }


    /**
     * 添加置顶
     *
     * @param annunciate
     *          Annunciate
     * @return JuiResult
     */
    @ResponseBody
    @RequestMapping("/isTop")
    public Result isTop(PtAnnouncement annunciate) {
        Result result = new Result();
        result.setCode(Result.SUCCESS);
        try {
            PtAnnouncement findOne=ptAnnouncementService.selectById(annunciate.getId());
            if (findOne != null) {
                findOne.setLastupDttm(new Date());
                findOne.setIsTop(annunciate.getIsTop());
                boolean update = ptAnnouncementService.updateById(findOne);
                if (update) {
                    if (findOne.getIsTop()==1) {
                        result.setMsg("置顶成功！");
                    } else {
                        result.setMsg("取消置顶成功！");
                    }
                }
            }
        } catch (Exception e) {
            result.setCode(Result.FAIL);
            result.setMsg("置顶失败！");
            logger.error("置顶通知公告失败", e);
        }
        return result;
    }

    /**
     * 批量删除
     *
     * @param ids
     *          要删除的id
     * @return Result
     */
    @RequestMapping("/batchdelete")
    @ResponseBody
    public Result batchdelete(String ids) {
        Result result = new Result();
        result.setCode(Result.SUCCESS);
        try {
            if (!StringUtils.isEmpty(ids)) {
                for (String id : ids.split(",")) {
                    ptAnnouncementService.deleteAnnunciate(Integer.valueOf(id));

                }
            }
            result.setMsg("删除成功");
            logger.info("删除成功");
        } catch (Exception e) {
            result.setCode(Result.FAIL);
            logger.info("删除失败", e);
            result.setMsg("删除失败");
        }
        return result;
    }
}
